const { MongoClient } = require('mongodb')

const url = 'mongodb://127.0.0.1:27017'

const client = new MongoClient(url)

const clientFun = async (c) => {
	await client.connect()
	const db = client.db('mytest')
	return db.collection(c)
}

const main = async () => {
	const cc = await clientFun('cc')

	/* // 新增
	// 新增一条
	let d = await cc.insertOne({ username: 'monica', age: 28 })
 */
	//  新增多条
	d = await cc.insertMany([
		{ username: '李梅', age: 11 },
		{ username: '李磊', age: 12 },
		{ username: '王蘑', age: 17 },
		{ username: '赵滴', age: 15 }
	])
	// console.log(d)

	// 修改
	// 修改单条
	/* await cc.updateOne(
		{ age: { $gt: 27 } },
		{ $set: { username: 'lisi' } }
	) */
	/* await cc.updateMany({ age: { $gt: 27 } }, { $set: { username: 'lisi' } }) */

	// 删除
	// 删除单条
	// await cc.deleteOne({ age: { $lt: 10 } })
	// 删除多条
	// await cc.deleteMany({ age: { $lt: 10 } })

	// 查询
	// 查询多条
	const result = await cc.find()
	console.log(await result.toArray(), (await result.toArray()).length)
	// 查询单条
	// const result = await cc.findOne({ age: { $gt: 28 } })
	// console.log(result)
}

main().finally(() => client.close())
